const storageService = require('../../../services/storage')
import * as comm from '../../../utils/common';
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    group: null,
    devices: [],
    loading: true,
    curWeek:-1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("group_devices onLoad...")
    if (options.groupInfo) {
      try {
        const group = JSON.parse(decodeURIComponent(options.groupInfo))
        this.setData({ group })
        this.loadGroupDevices(group.deviceIds)
      } catch (error) {
        console.error('解析编组信息失败', error)
        wx.showToast({
          title: '参数错误',
          icon: 'error',
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    } else if (options.did) {
      this.loadGroupData(options.did)
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error',
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log("group_devices onReady...")
    const $t = this;
    wx.$event.on("status", this, (obj) => {
      $t.chgStatus(obj);
    });
    wx.$event.on("getVal", this, (obj) => {
      $t.chgVal(obj);
    });

    $t.data.ckOnlineInterval = setInterval(() => {
      $t.ckOnline();
    }, 20000);

    this.getNowWeek();
    for (var i = 0; i < this.data.devices.length; i++) {
      let entityId = this.data.devices[i].deviceId
      let deviceType = this.data.devices[i].deviceType
      let data = storageService.getScheduleInfo(entityId)
      this.changeStartEndTime(i, data)
      let lightMode = storageService.getLightModeState(entityId)
      let isManualMode = lightMode == "manual"
      this.data.devices[i].isManualMode = isManualMode
      //行程模式默认开启
      this.data.devices[i].totalSwitch = !isManualMode
      if (this.data.devices[i].online == undefined) {
        this.data.devices[i].online = 0
      }
    }
    this.setData({
      devices: this.data.devices
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面显示时重新加载数据，确保状态同步
    if (this.data.group && this.data.group.id) {
      this.loadGroupData(this.data.group.id);
    } else if (this.data.group && this.data.group.deviceIds) {
      // 如果只有 groupInfo 传递，可能需要从 groupInfo 中获取 id
      // 或者在 onLoad 中确保 group.id 被正确设置
      // 为了简单起见，这里假设 group.id 总是可用的
      // 如果不是，需要调整 onLoad 的逻辑
    }
    // 如果是从 edit_group 返回，可能需要强制刷新
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    if (currentPage.options && currentPage.options.refresh === 'true') {
        if (this.data.group && this.data.group.id) {
             this.loadGroupData(this.data.group.id);
             // 重置 refresh 标志，避免不必要的重复刷新
             delete currentPage.options.refresh;
        }
    }
  },

  /**
   * 加载编组数据
   */
  loadGroupData: function (groupId) {
    const group = storageService.getDeviceInfo(groupId)

    if (!group) {
      wx.showToast({
        title: '编组不存在',
        icon: 'error',
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }

    // 使用storage服务获取设备列表，确保返回数组
    const devices=[]
    group.deviceIds.forEach(id=>{
      const device=storageService.getDeviceInfo(id)
      if(device){
        devices.push(device)
      }
    })

    // 确保编组内的设备状态与编组保持同步
    let hasChanges = false
    devices.forEach(device => {
      // 同步总开关状态、行程时间 和 灯光通道值
      //const deviceIndex = devices.findIndex(d => d.id === device.id); // 在外部查找索引
      let deviceNeedsUpdate = false;
          // 检查并同步 totalSwitch
          if (device.totalSwitch !== group.totalSwitch) {
            //targetDevice.totalSwitch = group.totalSwitch;
            device.totalSwitch = group.totalSwitch; // 更新当前页面数据源
            deviceNeedsUpdate = true;
          }
          // 检查并同步 startTime
          if (device.startTime !== group.startTime) {
            //targetDevice.startTime = group.startTime;
            device.startTime = group.startTime; // 更新当前页面数据源
            deviceNeedsUpdate = true;
          }
          // 检查并同步 endTime
          if (device.endTime !== group.endTime) {
            //targetDevice.endTime = group.endTime;
            device.endTime = group.endTime; // 更新当前页面数据源
            deviceNeedsUpdate = true;
          }

          // 检查并同步所有8个灯光通道值 TODO
         /* const channels = ['red', 'green', 'blue', 'white', 'lightBlue', 'royalBlue', 'purple', 'uv'];
          channels.forEach(channel => {
            const groupValue = group[channel] || 0;
            const deviceValue = targetDevice[channel] || 0;
            if (deviceValue !== groupValue) {
              targetDevice[channel] = groupValue;
              device[channel] = groupValue; // 更新当前页面数据源
              deviceNeedsUpdate = true;
            }
          });*/

          if (deviceNeedsUpdate) {
              hasChanges = true;
              console.log(`已同步编组[${groupId}]的状态和灯光值到设备[${device.id}]`);
          }
    });

    // 如果有变更，保存设备数据
    if (hasChanges) {
      //storageService.saveDevices(devices)
    }

    this.setData({
      group,
      devices,
      loading: false,
    })
  },

  /**
   * 导航到设备控制页面
   */
  navigateToModeSetting: function (e) {
    const index = e.currentTarget.dataset.index
    const device = this.data.groupDevices[index]

    if (!device || !device.deviceType) {
      console.error('无法获取设备信息或设备类型')
      wx.showToast({ title: '无法打开设备设置', icon: 'none' })
      return
    }

    // **根据设备类型构建 URL**
    let url = ''
    if (device.deviceType === 'freshwater_lamp') {
      url = `/packageFreshwater/freshwater_lamp/pages/mode_setting/mode_setting`
    } else {
      // 可以添加对其他设备类型的处理
      console.error(`未知的设备类型: ${device.deviceType}`)
      wx.showToast({ title: `不支持的设备类型: ${device.deviceType}`, icon: 'none' })
      return
    }

    // 传递完整的设备信息对象，而不仅仅是ID
    const deviceInfo = encodeURIComponent(JSON.stringify(device))
    wx.navigateTo({
      url: `${url}?deviceInfo=${deviceInfo}`,
    })
  },

  /**
   * 编辑编组
   */
  editGroup: function () {
    wx.navigateTo({
      url: `/pages/edit_group/edit_group?id=${this.data.group.id}`,
    })
  },

  /**
   * 处理设备开关状态变化
   */
  handleSwitchChange: function (e) {
    const { index, value, type } = e.detail
    //组模式下禁止单独操作
  },

  /**
   * 根据设备ID列表加载设备信息
   */
  loadGroupDevices: function (deviceIds) {
    if (!deviceIds || deviceIds.length === 0) {
      this.setData({
        groupDevices: [],
        loading: false,
      })
      return
    }

    // 导入storage服务和行程时间工具函数
    const storageService = require('../../../services/storage')
    const scheduleUtils = require('../../utils/schedule')
    const { logger } = require('../../utils/logger') // 导入日志

    // 获取所有设备
    let devices = storageService.getDevices()

    // 获取编组信息
    const groupId = this.data.group.id

    // 获取最新的编组数据
    const groups = storageService.getGroups()
    let updatedGroup = groups.find(g => g.id === groupId) // Use let for potential update

    if (!updatedGroup) {
      logger.error(`loadGroupDevices: 找不到编组[${groupId}]`)
      this.setData({
        groupDevices: [],
        loading: false,
      })
      return
    }

    // 筛选出编组内的设备
    let groupDevices = devices.filter(device => deviceIds.includes(device.id))

    // **获取编组的 deviceType**
    const groupDeviceType = updatedGroup.deviceType
    if (!groupDeviceType) {
      logger.error(`loadGroupDevices: 编组[${groupId}] 缺少 deviceType`)
      this.setData({ groupDevices: [], loading: false })
      return
    }

    // 检查编组是否处于自动模式，**传递 deviceType**
    const lightModeState = storageService.getLightModeState(groupId)
    const isAutoMode = lightModeState === 'auto'

    logger.info(
      `loadGroupDevices: 编组[${groupId}] 模式: ${lightModeState}, 设备数量: ${groupDevices.length}`
    )
    
    // 引入通道配置工具
    let channelConfigUtil;
    try {
      channelConfigUtil = require('../src/device_types/seawater_diy_lamp/utils/channel_config');
    } catch (e) {
      try {
        // 尝试不同的相对路径
        channelConfigUtil = require('../../src/device_types/seawater_diy_lamp/utils/channel_config');
      } catch (e2) {
        logger.error('无法加载通道配置工具模块', e2);
      }
    }
    
    // 获取编组的通道配置
    let groupChannelConfigs = null;
    if (channelConfigUtil && groupDeviceType === 'seawater_diy_lamp') {
      try {
        const { channelConfigs } = channelConfigUtil.loadEntityChannelConfigs(groupId, true, groupDeviceType);
        if (channelConfigs && Array.isArray(channelConfigs) && channelConfigs.length > 0) {
          groupChannelConfigs = channelConfigs;
          logger.info(`成功加载编组[${groupId}]的通道配置，共${channelConfigs.length}个通道`);
        }
      } catch (e) {
        logger.error(`加载编组[${groupId}]通道配置失败`, e);
      }
    }

    let activeStartTime = '--:--'
    let activeEndTime = '--:--'
    let activeSwitch = false
    let hasChangesInStorage = false // Track if storage needs saving

    if (isAutoMode) {
      // 1. 检查快捷模式行程
      const shortcutModeData = storageService.getShortcutModeData(groupId, true, groupDeviceType)
      const timerTasks = shortcutModeData.timerTasks || []
      const currentSchedule = scheduleUtils.getCurrentRunningSchedule(timerTasks)

      if (currentSchedule) {
        logger.info(
          `loadGroupDevices: 编组[${groupId}] 检测到活动快捷模式行程: ${currentSchedule.time} - ${currentSchedule.endTime}`
        )
        activeStartTime = currentSchedule.time
        activeEndTime = currentSchedule.endTime
        activeSwitch = true
      } else {
        // 2. 如果没有快捷模式行程，检查高级模式曲线
        const advancedModeData = storageService.getAdvancedModeData(groupId, true, groupDeviceType)
        const curves = advancedModeData.curves || []
        const hasEnabledCurve = curves.some(curve => curve.enabled)

        if (hasEnabledCurve) {
          logger.info(`loadGroupDevices: 编组[${groupId}] 检测到活动高级模式曲线`)
          activeStartTime = '00:00'
          activeEndTime = '24:00'
          activeSwitch = true
        } else {
          logger.info(`loadGroupDevices: 编组[${groupId}] 自动模式下无活动行程或曲线`)
          activeStartTime = '--:--'
          activeEndTime = '--:--'
          activeSwitch = false
        }
      }
    } else {
      // 手动模式
      logger.info(`loadGroupDevices: 编组[${groupId}] 处于手动模式`)
      activeStartTime = '--:--'
      activeEndTime = '--:--'
      // 在手动模式下，总开关状态应保持其在存储中的值
      activeSwitch = updatedGroup.totalSwitch
    }

    // --- 同步状态到存储和页面 ---

    // 1. 更新编组对象 (groups 列表)
    const groupIndex = groups.findIndex(g => g.id === groupId)
    if (groupIndex !== -1) {
      let groupNeedsUpdate = false
      if (groups[groupIndex].startTime !== activeStartTime) {
        groups[groupIndex].startTime = activeStartTime
        groupNeedsUpdate = true
      }
      if (groups[groupIndex].endTime !== activeEndTime) {
        groups[groupIndex].endTime = activeEndTime
        groupNeedsUpdate = true
      }
      if (groups[groupIndex].totalSwitch !== activeSwitch) {
        groups[groupIndex].totalSwitch = activeSwitch
        groupNeedsUpdate = true
      }

      if (groupNeedsUpdate) {
        logger.info(
          `loadGroupDevices: 更新存储中的编组对象[${groupId}]状态: switch=${activeSwitch}, time=${activeStartTime}-${activeEndTime}`
        )
        storageService.saveGroups(groups)
        updatedGroup = groups[groupIndex] // 更新本地副本以供 setData 使用
        hasChangesInStorage = true // Mark storage as changed
      }
    }

    // 2. 更新设备对象 (devices 列表 和 groupDevices 数组)
    let devicesNeedSaving = false
    groupDevices.forEach((device, index) => {
      const deviceId = device.id
      const deviceIndex = devices.findIndex(d => d.id === deviceId)
      let deviceInMemoryNeedsUpdate = false
      let deviceInStorageNeedsUpdate = false

      // **获取设备的 deviceType**
      const deviceType = device.deviceType
      if (!deviceType) {
         logger.warn(`loadGroupDevices: 设备[${deviceId}] 缺少 deviceType，跳过模式同步`)
      } else {
        // 同步灯光模式状态，**传递 deviceType**
        const deviceLightModeState = storageService.getLightModeState(deviceId)
      if (deviceLightModeState !== lightModeState) {
        logger.info(
          `loadGroupDevices: 同步设备[${deviceId}]的灯光模式状态: ${deviceLightModeState} -> ${lightModeState}`
        )
          storageService.saveLightModeState(deviceId, lightModeState, false, deviceType) // **传递 deviceType**
        // Note: storageService.saveLightModeState handles its own saving
        }
      }

      // 同步行程时间和开关状态
      if (device.startTime !== activeStartTime) {
        groupDevices[index].startTime = activeStartTime
        deviceInMemoryNeedsUpdate = true
        if (deviceIndex !== -1) devices[deviceIndex].startTime = activeStartTime
        deviceInStorageNeedsUpdate = true
      }
      if (device.endTime !== activeEndTime) {
        groupDevices[index].endTime = activeEndTime
        deviceInMemoryNeedsUpdate = true
        if (deviceIndex !== -1) devices[deviceIndex].endTime = activeEndTime
        deviceInStorageNeedsUpdate = true
      }
      if (device.totalSwitch !== activeSwitch) {
        groupDevices[index].totalSwitch = activeSwitch
        deviceInMemoryNeedsUpdate = true
        if (deviceIndex !== -1) devices[deviceIndex].totalSwitch = activeSwitch
        deviceInStorageNeedsUpdate = true
      }

      // 同步RGBW值
      // 检查是否需要同步RGBW值 - 两种情况：
      // 1. 总开关打开时，正常同步所有RGBW值
      // 2. 特殊情况：当编组的所有RGBW通道值都为0时，无论总开关状态如何，都强制同步这些0值
      if (
        (activeSwitch && updatedGroup) ||
        (updatedGroup &&
          updatedGroup.red === 0 &&
          updatedGroup.green === 0 &&
          updatedGroup.blue === 0 &&
          updatedGroup.white === 0 &&
          (updatedGroup.purple === 0 || updatedGroup.purple === undefined) &&
          (updatedGroup.uv === 0 || updatedGroup.uv === undefined))
      ) {
        // 检查设备的RGBW值是否与编组不同
        if (
          device.red !== updatedGroup.red ||
          device.green !== updatedGroup.green ||
          device.blue !== updatedGroup.blue ||
          device.white !== updatedGroup.white ||
          device.purple !== updatedGroup.purple ||
          device.uv !== updatedGroup.uv
        ) {
          // 特殊情况：当编组的所有RGBW通道值都为0时，记录特殊日志
          if (
            updatedGroup.red === 0 &&
            updatedGroup.green === 0 &&
            updatedGroup.blue === 0 &&
            updatedGroup.white === 0 &&
            (updatedGroup.purple === 0 || updatedGroup.purple === undefined) &&
            (updatedGroup.uv === 0 || updatedGroup.uv === undefined)
          ) {
            logger.info(`loadGroupDevices: 强制同步编组[${groupId}]的全零RGBWPUV值到设备[${deviceId}]`)
          } else {
            logger.info(`loadGroupDevices: 同步编组[${groupId}]的RGBWPUV到设备[${deviceId}]`)
          }

          groupDevices[index].red = updatedGroup.red
          groupDevices[index].green = updatedGroup.green
          groupDevices[index].blue = updatedGroup.blue
          groupDevices[index].white = updatedGroup.white
          groupDevices[index].purple = updatedGroup.purple || 0  // 同步紫光通道
          groupDevices[index].uv = updatedGroup.uv || 0          // 同步UV通道
          deviceInMemoryNeedsUpdate = true

          if (deviceIndex !== -1) {
            devices[deviceIndex].red = updatedGroup.red
            devices[deviceIndex].green = updatedGroup.green
            devices[deviceIndex].blue = updatedGroup.blue
            devices[deviceIndex].white = updatedGroup.white
            devices[deviceIndex].purple = updatedGroup.purple || 0  // 同步紫光通道
            devices[deviceIndex].uv = updatedGroup.uv || 0          // 同步UV通道
            deviceInStorageNeedsUpdate = true
          }
        }
      }

      // 同步通道配置信息到设备
      if (groupChannelConfigs && device.deviceType === 'seawater_diy_lamp' && channelConfigUtil) {
        try {
          // 直接应用通道配置到设备对象，更新UI显示
          const updatedDevice = channelConfigUtil.applyChannelConfigsToDevice(
            device, 
            groupChannelConfigs
          );
          
          // 更新本地设备数组中的设备对象
          Object.assign(device, updatedDevice);
          
          // 同时更新storage中的设备数据
          if (deviceIndex !== -1) {
            // 仅更新通道启用状态、颜色和名称属性
            devices[deviceIndex].redEnabled = updatedDevice.redEnabled;
            devices[deviceIndex].greenEnabled = updatedDevice.greenEnabled;
            devices[deviceIndex].blueEnabled = updatedDevice.blueEnabled;
            devices[deviceIndex].warmWhiteEnabled = updatedDevice.warmWhiteEnabled;
            devices[deviceIndex].lightBlueEnabled = updatedDevice.lightBlueEnabled;
            devices[deviceIndex].royalBlueEnabled = updatedDevice.royalBlueEnabled;
            devices[deviceIndex].purpleEnabled = updatedDevice.purpleEnabled;
            devices[deviceIndex].uvEnabled = updatedDevice.uvEnabled;
            devices[deviceIndex].moonWhiteEnabled = updatedDevice.moonWhiteEnabled;
            devices[deviceIndex].moonBlueEnabled = updatedDevice.moonBlueEnabled;
            
            // 颜色和名称属性
            devices[deviceIndex].redColor = updatedDevice.redColor;
            devices[deviceIndex].greenColor = updatedDevice.greenColor;
            devices[deviceIndex].blueColor = updatedDevice.blueColor;
            devices[deviceIndex].warmWhiteColor = updatedDevice.warmWhiteColor;
            devices[deviceIndex].lightBlueColor = updatedDevice.lightBlueColor;
            devices[deviceIndex].royalBlueColor = updatedDevice.royalBlueColor;
            devices[deviceIndex].purpleColor = updatedDevice.purpleColor;
            devices[deviceIndex].uvColor = updatedDevice.uvColor;
            devices[deviceIndex].moonWhiteColor = updatedDevice.moonWhiteColor;
            devices[deviceIndex].moonBlueColor = updatedDevice.moonBlueColor;
            
            // 通道名称（如果有）
            if (updatedDevice.redName) devices[deviceIndex].redName = updatedDevice.redName;
            if (updatedDevice.greenName) devices[deviceIndex].greenName = updatedDevice.greenName;
            if (updatedDevice.blueName) devices[deviceIndex].blueName = updatedDevice.blueName;
            if (updatedDevice.warmWhiteName) devices[deviceIndex].warmWhiteName = updatedDevice.warmWhiteName;
            if (updatedDevice.lightBlueName) devices[deviceIndex].lightBlueName = updatedDevice.lightBlueName;
            if (updatedDevice.royalBlueName) devices[deviceIndex].royalBlueName = updatedDevice.royalBlueName;
            if (updatedDevice.purpleName) devices[deviceIndex].purpleName = updatedDevice.purpleName;
            if (updatedDevice.uvName) devices[deviceIndex].uvName = updatedDevice.uvName;
            if (updatedDevice.moonWhiteName) devices[deviceIndex].moonWhiteName = updatedDevice.moonWhiteName;
            if (updatedDevice.moonBlueName) devices[deviceIndex].moonBlueName = updatedDevice.moonBlueName;
            
            hasChangesInStorage = true;
            logger.info(`已同步编组[${groupId}]的通道配置到设备[${deviceId}]`);
          }
        } catch (e) {
          logger.error(`应用通道配置到设备[${deviceId}]失败`, e);
        }
      }

      if (deviceInStorageNeedsUpdate) {
        devicesNeedSaving = true // Mark devices list for saving if any device changed
      }
    })

    // 将两个保存标志合并
    const needToSaveDevices = devicesNeedSaving || hasChangesInStorage;

    // 更新页面数据
    this.setData({
      groupDevices,
      group: updatedGroup, // 使用可能已更新的编组对象
      loading: false,
    })

    // 完成所有设备的更新后，如果有变更，保存设备数据
    if (needToSaveDevices) {
      const success = storageService.saveDevices(devices);
      if (success) {
        logger.info(`成功保存了${groupDevices.length}个设备的更新数据，包括通道配置同步和RGBW值同步`);
      } else {
        logger.error('保存设备数据失败');
      }
    }
  },

  /**
   * 处理设备卡片触发的导航事件
   */
  handleNavigateEvent: function(e) {
    const device = e.detail.device;
    if (!device || !device.deviceType) {
      console.error('handleNavigateEvent: 无法获取设备信息或设备类型');
      wx.showToast({ title: '无法打开设备信息', icon: 'none' });
      return;
    }

    // 根据设备类型构建 URL
    let url = '';
    if (device.deviceType === 'freshwater_lamp') {
      url = `/packageFreshwater/freshwater_lamp/pages/device_info/device_info`;
    } else if (device.deviceType === 'seawater_lamp') {
      url = `/packageFreshwater/seawater_lamp/pages/device_info/device_info`;
    } else if (device.deviceType === 'seawater_diy_lamp') {
      url = `/src/device_types/seawater_diy_lamp/pages/device_info/device_info`;
    } else if (device.deviceType === 'freshwater_diy_lamp') {
      url = `/src/device_types/freshwater_diy_lamp/pages/device_info/device_info`;
    } else {
      console.error(`handleNavigateEvent: 未知的设备类型: ${device.deviceType}`);
      wx.showToast({ title: `不支持的设备类型: ${device.deviceType}`, icon: 'none' });
      return;
    }

    const deviceInfo = encodeURIComponent(JSON.stringify(device));
    wx.navigateTo({
      url: `${url}?deviceInfo=${deviceInfo}`,
      fail: (err) => {
        console.error('handleNavigateEvent: 页面跳转失败', err);
        wx.showToast({ title: '页面跳转失败', icon: 'none' });
      }
    });
  },

  /**
   * 导航到设备信息页面
   */
  navigateToDeviceInfo: function (e) {
    const index = e.currentTarget.dataset.index
    const device = this.data.groupDevices[index]

    if (!device || !device.deviceType) {
      console.error('无法获取设备信息或设备类型')
      wx.showToast({ title: '无法打开设备信息', icon: 'none' })
      return
    }

    // 根据设备类型构建 URL
    let url = ''
    if (device.deviceType === 'freshwater_lamp') {
      url = `/packageFreshwater/freshwater_lamp/pages/device_info/device_info`
    } else if (device.deviceType === 'seawater_lamp') {
      url = `/packageFreshwater/seawater_lamp/pages/device_info/device_info`
    } else if (device.deviceType === 'seawater_diy_lamp') {
      url = `/src/device_types/seawater_diy_lamp/pages/device_info/device_info`
    } else {
      // 可以添加对其他设备类型的处理
      console.error(`未知的设备类型: ${device.deviceType}`)
      wx.showToast({ title: `不支持的设备类型: ${device.deviceType}`, icon: 'none' })
      return
    }

    // 传递完整的设备信息对象
    const deviceInfo = encodeURIComponent(JSON.stringify(device))
    wx.navigateTo({
      url: `${url}?deviceInfo=${deviceInfo}`,
    })
  },

  chgStatus(obj) {
    for (var i = 0; i < this.data.devices.length; i++) {
      if (this.data.devices[i].topicSub == obj.topic) {
        let str1 = "devices[" + i + "].time";
        let str2 = "devices[" + i + "].online";
        let str3 = "devices[" + i + "].fanStatus";
        let str4 = "devices[" + i + "].temperature";
        let data = {
          [str1]: Date.now(),
          [str2]: 1,
          [str3]: obj.msg["fanStarted"] != undefined && obj.msg["fanStarted"] == "1" ? "07" : "0",
          [str4]: obj.msg["tempNow"],
        }
        if (this.data.devices[i].isManualMode) {
          let str5 = "devices[" + i + "].totalSwitch";
          data[[str5]] = obj.msg["hasV"] == "1"
        }
        this.setData(data);
        break;
      }
    }
  },

  chgVal(obj) {
    for (var i = 0; i < this.data.devices.length; i++) {
      if (this.data.devices[i].topicSub == obj.topic) {
        const child = this.selectComponent("#card" + this.data.devices[i].deviceId);
        child.initVal(obj)
        break;
      }
    }
  },

  ckOnline() {
    let now = Date.now();
    for (var i = 0; i < this.data.devices.length; i++) {
      let obj = this.data.devices[i];
      if (obj.online == 0) {
        continue;
      }
      if ((now - obj.time) / 1000 > 15) {
        let str2 = "devices[" + i + "].online";
        this.setData({
          [str2]: 0
        });
      }
    }
  },
  getNowWeek() {
    const currentDate = new Date();
    let currentDay = currentDate.getDay();
    if (currentDay == 0) {
      currentDay = 6;
    } else {
      currentDay--;
    }
    //console.log(currentDay);
    if (this.data.curWeek != currentDay) {
      this.setData({
        curWeek: currentDay
      })
    }
  },
  changeStartEndTime(idx, data) {
    console.log("changeStartEndTime",idx,data)
    let startTime = "--:--"
    let endTime = "--:--"
    try {
      if (comm.isEmptyObj(data)) {
        return
      }
      let tlsArr = data.tls
      let weekArr = data.w
      let index = weekArr[this.data.curWeek]
      if (index < 0) {
        return
      }
      let arr = tlsArr[index]
      let min = 240000
      let max = 0
      for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < arr[i].length; j++) {
          if (arr[i][j][0] < min) {
            min = arr[i][j][0]
          }
          if (arr[i][j][0] > max) {
            max = arr[i][j][0]
          }
        }
      }

      let minH = parseInt(min / 10000)
      let minM = (min % 10000) / 100
      let maxH = parseInt(max / 10000)
      let maxM = (max % 10000) / 100
      if (minH < 10) {
        minH = "0" + minH
      }
      if (minM < 10) {
        minM = "0" + minM
      }
      if (maxH < 10) {
        maxH = "0" + maxH
      }
      if (maxM < 10) {
        maxM = "0" + maxM
      }
      startTime = minH + ":" + minM
      endTime = maxH + ":" + maxM
    } finally {
      this.setData({
        [`devices[${idx}].startTime`]: startTime,
        [`devices[${idx}].endTime`]: endTime
      })
    }
  },
  onUnload: function () {
    console.log("group_devices onUnload...")
    wx.$event.remove("status", this);
    wx.$event.remove("getVal", this);
    clearInterval(this.data.ckOnlineInterval);
    this.data.ckOnlineInterval = null;
    clearInterval(this.data.wkInterval);
    this.data.wkInterval = null;
  },







})
